
package tv.youxing.android.ui;
/**
 * Created by apple on 17/3/14.
 */

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.toolbox.Loger;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import tv.youxing.android.Interface.CustomToobarImp;
import tv.youxing.android.R;
import tv.youxing.android.adapter.AddAttachmentAdapter;
import tv.youxing.android.base64.BASE64Encoder;
import tv.youxing.android.custom.CustomDialog;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.custom.CustomToolbar;
import tv.youxing.android.custom.imageview.PictureUtil;
import tv.youxing.android.entity.AddDynamicModel;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.PhotoUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;

/**
 * 项目名：   Dbs
 * 包名：     com.lizi.dbs.ui
 * 文件名：   UploadSchemeActivity
 * 创建者：   叶克武
 * 创建时间： 17/3/14 下午5:17
 * 描述：    发表动态
 */
public class AddDynamicActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.et_scheme_content)
    EditText mContextEt;
    @BindView(R.id.noScrollgridview)
    GridView mGridView;
    @BindView(R.id.tb)
    CustomToolbar mCustomToollbar;

    List<AddDynamicModel> mImageList = new ArrayList<>();
    AddAttachmentAdapter mAdapter;

    private KProgressHUD hud;

    private CustomDialog mDialog_avatar;
    //头像更新的相机操作
    private Button btn_camera;
    private Button btn_picture;
    private Button btn_cancel;


    private static final int PHOTO_CARMERA = 1;//拍照
    private static final int PHOTO_PICK = 2;//选择
    private static final int PHOTO_CUT = 3;//裁剪

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_dynamic);
        ButterKnife.bind(this);


        initView();
        initData();
    }

    private void initView() {
        mCustomToollbar.setRightTextClickLister(new CustomToobarImp.right_text() {
            @Override
            public void onclick() {

                if (mImageList.size() > 0) {
                    for (int i = 0; i < mImageList.size(); i++) {
                        System.out.println("mImageList"+ mImageList.get(i).getImg_path());
                    }
                }

//                sendData();
            }
        });

        mDialog_avatar = new CustomDialog(this, 400
                , ViewGroup.LayoutParams.MATCH_PARENT, R.layout.dialog_photo, R.style.Theme_dialog, Gravity.BOTTOM, R.style.pop_anim_style);
        mDialog_avatar.setCancelable(true);
        btn_camera = (Button) mDialog_avatar.findViewById(R.id.btn_camera);
        btn_camera.setOnClickListener(this);
        btn_picture = (Button) mDialog_avatar.findViewById(R.id.btn_picture);
        btn_picture.setOnClickListener(this);
        btn_cancel = (Button) mDialog_avatar.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(this);
    }

    // 创建一个以当前系统时间为名称的文件，防止重复
    private File tempFile = new File(Environment.getExternalStorageDirectory(),
            getPhotoFileName());

    // 使用系统当前日期加以调整作为照片的名称
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("'PNG'_yyyyMMdd_HHmmss");
        return sdf.format(date) + ".png";
    }

    private void initData() {
        mAdapter = new AddAttachmentAdapter(this, this, mImageList);
        mGridView.setAdapter(mAdapter);

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mDialog_avatar.show();
            }
        });
    }


    // 调用系统相册
    public void startPick() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, PHOTO_PICK);
    }


    // 调用系统裁剪
    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以裁剪
        intent.putExtra("crop", true);
        // aspectX,aspectY是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY是裁剪图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        // 设置是否返回数据
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CUT);
    }


    /**
     * @param bytes
     * @return
     * @Description long转文件大小M单位方法
     * @author temdy
     */
    public String bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
        return returnValue + "";
    }


    /**
     * 发布
     */
    void sendData() {
        String content = UtilTools.getString(mContextEt);

        if (content.equals("") && content.length() <= 0) {
            CustomToast.INSTANCE.showToast("内容不能为空");
            return;
        }


//        int str_index = tempFile.getAbsolutePath().indexOf(".")+1;//.的索引
//        String img_type = tempFile.getAbsolutePath().substring(str_index);//图片的类型


        hideInputManager(getApplicationContext());


        final HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getApplicationContext(), AppConst.TOKEN, ""));
        params.put("content", content);
//        params.put("image_1","data:image/"+img_type+";base64,"+UtilTools.bitmapToBase64(bitmap));
        GetPathFromUri4kitkat getPathFromUri4kitkat = new GetPathFromUri4kitkat();


        String url = StaticClass.PublicationDynamics;
        PostFormBuilder u = OkHttpUtils
                .post()
                .url(url);
        u.addHeader("Authorization", "Bearer " + ShareUtils.getString(getApplicationContext(), AppConst.TOKEN, ""));
        u.addParams("content", "" + content);

        if (mImageList.size() > 0) {
            for (int i = 0; i < mImageList.size(); i++) {
                //使用uri
//                String path = getPathFromUri4kitkat.getPath(AddDynamicActivity.this,mImageList.get(i).getImage_uri());
                //使用file path
                String path = "file://" + mImageList.get(i).getImg_path();
                int str_index = path.indexOf(".") + 1;//.的索引
                String img_type = path.substring(str_index);//图片的类型


                final String prefix = path.substring(path.lastIndexOf(".") + 1);


                //不压缩上传
//                params.put("image_"+(i+1), "data:image/"+img_type+";base64,"+Bitmap2StrByBase64(decodeUriAsBitmap(mImageList.get(i).getImage_uri())));


                //压缩上传
//                try {
//                    params.put("image_"+(i+1), "data:image/"+img_type+";base64,"+Bitmap2StrByBase64(getBitmapFormUri(AddDynamicActivity.this,mImageList.get(i).getImage_uri())));
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }

//                params.put("image_"+(i+1), "data:image/"+img_type+";base64,"+UtilTools.Bitmap2StrByBase64(BitmapFactory.decodeFile(mImageList.get(i).getImg_path())));

                File file = new File(mImageList.get(i).getImg_path());



                //1M=1024k=1048576字节
                if (file.length() < (1 * 1048576)) {
                    L.d("不压缩上传");
//                    params.put("image_" + (i + 1), "data:image/" + img_type + ";base64," + PictureUtil.bitmapToString(mImageList.get(i).getImg_path()));
//                        params.put("image_" + (i + 1), "data:image/" + prefix + ";base64," + GetImageStr(mImageList.get(i).getImg_path()));
//                    sendImage(BitmapFactory.decodeFile(mImageList.get(i).getImg_path()));
                    u.addParams("image_" + (i + 1), "data:image/" + prefix + ";base64," + GetImageStr(mImageList.get(i).getImg_path()));


                    Logger.d("base64:" + GetImageStr(mImageList.get(i).getImg_path()));

                } else {
                    L.d("压缩上传");
//                    params.put("image_" + (i + 1), "data:image/" + prefix + ";base64," + PictureUtil.bitmapToString(mImageList.get(i).getImg_path()));
                    u.addParams("image_" + (i + 1), "data:image/" + prefix + ";base64," + PictureUtil.bitmapToString(mImageList.get(i).getImg_path()));
                    Logger.d("base64:" + GetImageStr(PictureUtil.bitmapToString(mImageList.get(i).getImg_path())));

                }


//                L.d("image size:" +);
            }
        }


        showProgress("上传中");



        u.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomToast.INSTANCE.showToast(e.getMessage());
                L.d("error:" + e.getMessage());
                hideProgress();
            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    int code = (int) jsonObject.get("code");

                    if (code == AppConst.TOKENERROR) {
                        startActivity(new Intent(AddDynamicActivity.this,LoginActivity.class));
                        return;
                    }

                    if (code == 200) {
                        hideProgress();
                        EventBus.getDefault().post("add");
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }
        });


//        RxVolley.post(StaticClass.PublicationDynamics, params, new HttpCallback() {
//            @Override
//            public void onSuccess(String t) {
//                System.out.println(t);
//
//                Model model = GsonUtils.GsonToBean(t, Model.class);
//
//
//                L.d("scr:" + t);
//
//
//                if (model.getCode() == 200) {
//                    CustomToast.INSTANCE.showToast("发表成功");
//                    EventBus.getDefault().post("add");
//                    finish();
//                } else {
//                    System.out.println("error:" + t);
//                    CustomToast.INSTANCE.showToast("发表失败:" + model.getCode());
//                }
//            }
//
//
//            @Override
//            public void onFailure(VolleyError error) {
//                super.onFailure(error);
//                System.out.println("error:" + error.getMessage());
//                CustomToast.INSTANCE.showToast("发表失败");
//                hideProgress();
//            }
//        });

    }

    // 隐藏软键盘
    public void hideInputManager(Context ct) {
        try {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) ct)
                    .getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
        }
    }


    public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;

        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    private void sendImage(Bitmap bm) {


        if (bm == null) {
            return;
        }

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 60, stream);
        byte[] bytes = stream.toByteArray();
        String img = new String(Base64.encodeToString(bytes, Base64.DEFAULT));


        HttpParams params = new HttpParams();
        params.put("img", img);

        RxVolley.post("http://192.168.2.230:9090/load.php", params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                Loger.debug("请求到的数据:" + t);
            }
        });
    }


    /**
     * 通过uri获取图片并进行压缩
     *
     * @param uri
     */
    public static Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
        InputStream input = ac.getContentResolver().openInputStream(uri);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;
        //图片分辨率以480x800为标准
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / ww);
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / hh);
        }
        if (be <= 0)
            be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = ac.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();

        return compressImage(bitmap);//再进行质量压缩
    }


    public void showProgress(String message) {
        if (hud == null) {
            hud = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setLabel(message)
                    .setCancellable(true);
        }
        if (!hud.isShowing()) {
            hud.show();
        }
    }

    public void hideProgress() {
        if (hud != null && hud.isShowing()) {
            hud.dismiss();
        }
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_camera:
                if (hasSdcard()) {
                    imageUri = Uri.fromFile(fileUri);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        imageUri = FileProvider.getUriForFile(this, "com.zz.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                    PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                } else {
                    CustomToast.INSTANCE.showToast("设备没有SD卡");
                }
                break;
            case R.id.btn_picture:
                PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                break;
            case R.id.btn_cancel:
                mDialog_avatar.dismiss();
                break;
        }
    }


    public class GetPathFromUri4kitkat {

        /**
         * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
         */
        @SuppressLint("NewApi")
        public String getPath(final Context context, final Uri uri) {

            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }

                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{split[1]};

                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }

            return null;
        }

        /**
         * Get the value of the data column for this Uri. This is useful for
         * MediaStore Uris, and other file-based ContentProviders.
         *
         * @param context       The context.
         * @param uri           The Uri to query.
         * @param selection     (Optional) Filter used in the query.
         * @param selectionArgs (Optional) Selection arguments used in the query.
         * @return The value of the _data column, which is typically a file path.
         */
        public String getDataColumn(Context context, Uri uri, String selection,
                                    String[] selectionArgs) {

            Cursor cursor = null;
            final String column = "_data";
            final String[] projection = {column};

            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int column_index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is ExternalStorageProvider.
         */
        public boolean isExternalStorageDocument(Uri uri) {
            return "com.android.externalstorage.documents".equals(uri.getAuthority());
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is DownloadsProvider.
         */
        public boolean isDownloadsDocument(Uri uri) {
            return "com.android.providers.downloads.documents".equals(uri.getAuthority());
        }

        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is MediaProvider.
         */
        public boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }
    }


    class Model {

        /**
         * status : 成功
         * result : {}
         * code : 200
         */

        private String status;
        private ResultBean result;
        private int code;

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public ResultBean getResult() {
            return result;
        }

        public void setResult(ResultBean result) {
            this.result = result;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public class ResultBean {
        }
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }



    private static final int output_X = 480;
    private static final int output_Y = 480;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);


        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST://拍照完成回调
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        {
                            newUri = FileProvider.getUriForFile(this, "com.zz.fileprovider", new File(newUri.getPath()));
                        }
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    } else {
                        CustomToast.INSTANCE.showToast("设备没有SD卡");
                    }
                    break;
                case CODE_RESULT_REQUEST://裁剪完成后回调
                    Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(this.getContentResolver(), bitmap, null,null));
                    mAdapter.addImgPathList(UtilTools.getUriToPath(uri,AddDynamicActivity.this));
                    mAdapter.notifyDataSetChanged();

                    if (mDialog_avatar.isShowing()) {
                        mDialog_avatar.dismiss();
                    }

                    break;
            }
        }


//        if (requestCode == 1) {
//            if (data != null) {
//                Uri uri = data.getData();// find uri
//
//                // Imagepxh image = new Imagepxh(uri);
//                // list.add(image);
//
//                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
//
//
////
//                for (int i = 0; i < path.size(); i++) {
//                    mAdapter.addImgPathList(path.get(i));
//                }
//
////                mAdapter.addList(uri);// list.add();
//                mAdapter.notifyDataSetChanged();
//
//                // Toast.makeText(this, "成功获取照片", Toast.LENGTH_LONG).show();
//
//            } else {
//                //Toast.makeText(this, "用户返回了", Toast.LENGTH_LONG).show();
//            }


        }


//        switch (requestCode) {
//            case PHOTO_CARMERA:
//                startPhotoZoom(Uri.fromFile(tempFile), 300);
//                break;
//            case PHOTO_PICK:
//                if (null != data) {
////                    startPhotoZoom(data.getData(), 300);
////                    startActivityForResult(intent, PHOTO_CUT);
//                }
//                if (data != null) {
//                    Uri uri = data.getData();// find uri
//
////                 Imagepxh image = new Imagepxh(uri);
////                 list.add(image);
//                    mAdapter.addList(uri);// list.add();
//                    mAdapter.notifyDataSetChanged();
//
//                    Toast.makeText(this, "成功获取照片", Toast.LENGTH_LONG).show();
//                } else {
//                    Toast.makeText(this, "用户返回了", Toast.LENGTH_LONG).show();
//                }
//                break;
//            //拍照或者选择照片确定之后调用
//            case PHOTO_CUT:
//                if (data != null) {
//                Uri uri = data.getData();// find uri
//
////                 Imagepxh image = new Imagepxh(uri);
////                 list.add(image);
//                mAdapter.addList(uri);// list.add();
//                mAdapter.notifyDataSetChanged();
//
//                Toast.makeText(this, "成功获取照片", Toast.LENGTH_LONG).show();
//            } else {
//                Toast.makeText(this, "用户返回了", Toast.LENGTH_LONG).show();
//            }
//                break;
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.action_add_dynamic) {
            sendData();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_add_dynamic, menu);
        return true;
    }















    // *************************** 相机操作 ****************************//


    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }





}
